// 共享工具模块
const CowHorseClock = {
    // 默认设置
    defaultSettings: {
        payDate: 1,
        monthlySalary: 0,
        yearlyBonus: 0,
        includeWeekends: false
    },

    // 获取存储的设置
    getStoredSettings() {
        const settings = localStorage.getItem('cowHorseClockSettings');
        return settings ? JSON.parse(settings) : { ...this.defaultSettings };
    },

    // 保存设置到localStorage
    saveSettings(settings) {
        localStorage.setItem('cowHorseClockSettings', JSON.stringify(settings));
    },

    // 计算工作日
    calculateWorkdays(startDate, endDate, includeWeekends) {
        let workdays = 0;
        const currentDate = new Date(startDate);
        
        // 将时间设置为工作日开始时间
        currentDate.setHours(8, 0, 0, 0);
        
        while (currentDate <= endDate) {
            // 如果不计算周末，则跳过周末
            if (!includeWeekends) {
                const dayOfWeek = currentDate.getDay();
                // 0是周日，6是周六
                if (dayOfWeek !== 0 && dayOfWeek !== 6) {
                    workdays++;
                }
            } else {
                workdays++;
            }
            
            // 移动到下一天
            currentDate.setDate(currentDate.getDate() + 1);
        }
        
        return workdays;
    },

    // 获取当前工资周期的开始和结束日期
    getCurrentPayPeriod(payDate) {
        const today = new Date();
        const year = today.getFullYear();
        const month = today.getMonth();
        
        // 发薪日的日期对象
        let payDateObj = new Date(year, month, payDate);
        
        // 如果今天的日期已经过了发薪日，则发薪日应该是下个月
        if (today.getDate() > payDate) {
            payDateObj = new Date(year, month + 1, payDate);
        }
        
        // 结束日期是发薪日当天
        const endDate = new Date(payDateObj);
        endDate.setHours(18, 0, 0, 0);
        
        // 开始日期是上一个发薪日的第二天
        const startDate = new Date(payDateObj);
        startDate.setMonth(startDate.getMonth() - 1);
        startDate.setDate(startDate.getDate() + 1);
        startDate.setHours(8, 0, 0, 0);
        
        return { startDate, endDate };
    },

    // 计算工资信息
    calculateSalaryInfo() {
        const settings = this.getStoredSettings();
        const { payDate, monthlySalary, yearlyBonus, includeWeekends } = settings;
        
        // 计算工资周期
        const { startDate, endDate } = this.getCurrentPayPeriod(payDate);
        
        // 计算工作日数量
        const totalWorkdays = this.calculateWorkdays(startDate, endDate, includeWeekends);
        
        // 计算本月工作日数量
        const today = new Date();
        const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
        const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        const monthTotalWorkdays = this.calculateWorkdays(monthStart, monthEnd, includeWeekends);
        
        // 计算本月已工作天数
        const monthWorkedDays = this.calculateWorkdays(monthStart, today, includeWeekends);
        
        // 计算日薪
        const dailyWage = monthTotalWorkdays > 0 ? monthlySalary / monthTotalWorkdays : 0;
        
        // 计算今天是否是工作日
        today.setHours(12, 0, 0, 0); // 设置为中午避免时区问题
        let todayIsWorkday = true;
        if (!includeWeekends) {
            const dayOfWeek = today.getDay();
            if (dayOfWeek === 0 || dayOfWeek === 6) {
                todayIsWorkday = false;
            }
        }
        
        // 计算今天已得工资
        const todaySalary = todayIsWorkday ? dailyWage : 0;
        
        // 计算本月已得工资
        const monthlySalaryEarned = monthWorkedDays * dailyWage;
        
        // 计算总工资（当前周期）
        const totalSalary = totalWorkdays * dailyWage;
        
        // 计算年终奖（按天计算）
        const yearWorkdays = this.calculateWorkdays(
            new Date(today.getFullYear(), 0, 1),
            new Date(today.getFullYear(), 11, 31),
            includeWeekends
        );
        const dailyBonus = yearWorkdays > 0 ? yearlyBonus / yearWorkdays : 0;
        const todayBonus = todayIsWorkday ? dailyBonus : 0;
        
        // 计算年薪（含年终奖）
        const yearlySalary = monthlySalary * 12 + yearlyBonus;
        
        return {
            monthlySalary,
            dailyWage,
            todaySalary: todaySalary + todayBonus,
            monthlySalaryEarned,
            totalSalary,
            payDate,
            yearlyBonus,
            yearlySalary,
            todayBonus
        };
    },

    // 格式化金额
    formatCurrency(amount) {
        return `¥${amount.toFixed(2)}`;
    },

    // 显示提示信息
    showToast(message, type = 'success') {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        
        // 添加样式
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: ${type === 'success' ? '#34c759' : '#ff3b30'};
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;
        
        // 添加到页面
        document.body.appendChild(toast);
        
        // 显示动画
        setTimeout(() => {
            toast.style.opacity = '1';
        }, 10);
        
        // 3秒后移除
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 3000);
    }
};